package config

import (
	"encoding/json"
	"fmt"
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"os"
)

const (
	// SystemAdmin 系统管理员.
	SystemAdmin = 1
	// CompanyAdmin 公司管理员.
	CompanyAdmin = 2
	// OrdinaryUsers 普通用户.
	OrdinaryUsers = 3
	// EndUser 终端用户
	EndUser  = 4
	ConfPath = "../config"
	AirDev   = "../airdev"
	FileName = "config.yaml"
)

// socket.io event
var (
	EventNotice           = "EventNotice"
	EventAlarm            = "alarm"
	EventSubscribeAlarm   = "SubscribeAlarm"
	EventUnSubscribeAlarm = "UnSubscribeAlarm"
)

var Conf = new(Config)
var ConfJson ModelConf

//ModelConf 配置的物模型ID, 查询数据使用
type ModelConf struct {
	CurveJson map[string][]string `json:"curve_json"`
	HisJson   map[string][]string `json:"his_json"`
}

func init() {
	exist, err := PathExists(ConfPath + "/" + FileName)
	if err != nil {
		fmt.Printf("get dir error![%v]\n", err)
		return
	}
	if !exist {
		// 系统默认配置.
		Conf.Server.Version = "v1"
		Conf.Server.Port = "28081"
		Conf.Server.UploadPath = "./static"
		Conf.Server.Prefix = "cms"
		Conf.Server.GoroutineNum = 20
		// 日志
		Conf.Logs.LogName = "auth.log"
		Conf.Logs.Level = "info"
		// 默认账户
		Conf.DefaultUser.UserName = "admin"
		Conf.DefaultUser.PassWord = "admin@123"
		Conf.DefaultUser.UserType = 1            // 1.系统管理员 2.公司管理员 3.普通用户 4.终端
		Conf.Qt.VideoPath = "../Firmware/run.sh" // 打开视频地址
		Conf.Qt.ConfigPath = "../Firmware/config.json"
		Conf.Qt.Key = "8f24e0f08c5da0d887a794f2bb8f7bfe"
		Conf.Qt.Url = "http://127.0.0.1:28081/cms/v1/qt/api"
		save(Conf, ConfPath+"/"+FileName)
		saveData := `{"curve_json":{"m_so2":["so2"],"m_nox":["nox"],"m_co":["co"],"m_o3":["o3"],"m_pm10":["pm"],"m_pm25":["pm"],"m_total_N":["Measured value"],"m_total_P":["Measured value"],"m_NHN":["Measured value"],"m_COD":["Measured value"],"m_pH":["pH","temperature"]},"his_json":{"m_nox":["no","no2","nox","status"],"m_co":["co","status"],"m_so2":["so2","status"],"m_o3":["o3","status"],"m_pm10":["pm","status"],"m_pm25":["pm","status"]}}`
		saveJson(saveData, ConfPath+"/"+"config.json")
	} else {
		yamlFile, err := ioutil.ReadFile(ConfPath + "/" + FileName)
		if err != nil {
			panic(err)
		}
		err = yaml.Unmarshal(yamlFile, Conf)
		if err != nil {
			panic(err)
		}
	}
	// 获取 json 配置
	b, _ := ioutil.ReadFile(ConfPath + "/" + "config.json")
	json.Unmarshal(b, &ConfJson)
}

type Database struct {
	User         string `yaml:"user"`
	Host         string `yaml:"host"`
	Password     string `yaml:"pwd"`
	Port         string `yaml:"port"`
	Dbname       string `yaml:"dbname"`
	Type         string `yaml:"type"`
	MaxIdleConns int    `yaml:"max_idle_conns"` //  设置空闲连接池中连接的最大数量
	MaxOpenConns int    `yaml:"max_open_conns"` //  设置了连接可复用的最大时间。
	MaxLifetime  int64  `yaml:"max_lifetime"`   // 设置了连接可复用的最大时间
}

type Config struct {
	Server struct {
		Port         string `yaml:"port"`
		Version      string `yaml:"version"`
		GoroutineNum int    `yaml:"goroutine_num"`
		UploadPath   string `yaml:"upload_path"`
		Prefix       string `yaml:"prefix"`
	}
	//Redis struct {
	//	Host     string `yaml:"host"`
	//	Port     string `yaml:"port"`
	//	Password string `yaml:"password"`
	//	Db       int    `yaml:"db"`
	//	Pool     int    `yaml:"pool"`
	//}
	DefaultUser struct {
		UserName string `yaml:"username"`
		PassWord string `yaml:"password"`
		UserType int    `yaml:"usertype"`
	}
	//Db   Database `yaml:"db"`
	Logs struct {
		Level   string `yaml:"level"`
		LogName string `yaml:"log_name"`
	}
	Qt struct {
		VideoPath  string `yaml:"video_path"`
		ConfigPath string `yaml:"config_path"`
		Key        string `yaml:"key"`
		Url        string `yaml:"url"`
	}
}

func save(option interface{}, filename string) {
	os.Mkdir(ConfPath, os.ModePerm)
	filePtr, err := os.Create(filename)
	if err != nil {
		fmt.Println("文件创建失败", err.Error())
		return
	}
	defer filePtr.Close()
	d, _ := yaml.Marshal(option)
	filePtr.WriteString(string(d))
}

func saveJson(option interface{}, filename string) {
	os.Mkdir(ConfPath, os.ModePerm)
	filePtr, err := os.Create(filename)
	if err != nil {
		fmt.Println("文件创建失败", err.Error())
		return
	}
	defer filePtr.Close()
	filePtr.WriteString(option.(string))
}

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

type brandProtocol struct {
	ModelId      string `json:"model_id"`
	ProtocolPath string `json:"protocol_path"`
}

func GetAirDev() []byte {
	data, err := os.ReadFile(AirDev)
	if err != nil {
		fmt.Printf("read json file err:" + err.Error())
	}
	if os.IsNotExist(err) {
		return nil
	}
	return data
}
